package com.checkoutcheckins.client.callbacks;

import com.checkoutcheckins.client.data.DataContainer;
import com.checkoutcheckins.client.data.foursquare.FoursquareCheckins;
import com.checkoutcheckins.client.rpc.CheckinResponse;
import com.checkoutcheckins.client.services.FoursquareServiceAsync;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HTML;

public class DatabaseCheckinsCallback implements AsyncCallback<CheckinResponse> {

	private boolean getFoursquareCheckins = false;

	private DataContainer dataContainer = null;

	private FoursquareServiceAsync fsSvc = null;

	public DatabaseCheckinsCallback(FoursquareServiceAsync fsSvc,
			DataContainer dataContainer, boolean getFoursquareCheckins) {
		this.getFoursquareCheckins = getFoursquareCheckins;
		this.dataContainer = dataContainer;
		this.fsSvc = fsSvc;
	}

	public void onFailure(Throwable caught) {
		dataContainer.getStatusPanel().showErrorMessage(caught.getMessage(),
				false);
	}

	@Override
	public void onSuccess(CheckinResponse result) {

		// Add checkins to list
		dataContainer.getFoursquareCheckins().addCheckins(
				result.getCheckinList());

		if (result.getCheckinList().size() != 0) {
			dataContainer.updateFoursquareCheckins();
		}

		System.out.println(result.getMessage());
		System.out.println("retrieved size: "
				+ dataContainer.getFoursquareCheckins().getCheckins().size());

		// if not finished show timed update message, get more from db
		if (!result.isFinished()) {
			dataContainer.getStatusPanel().showLoadMessage(result.getMessage(),
					true);
			dataContainer.getStatusPanel().showLoadMessage(
					"Getting additional stored checkins", false);
			fsSvc.getCheckinsFromDatabase(result.getFoursquareId(), result
					.getCheckinList().size(), this);
		}

		// if finished show timed finish message, get foursquare checkins
		else if (getFoursquareCheckins) {
			System.out.println("getting checkins from foursquare");
			dataContainer.getStatusPanel().showLoadMessage(result.getMessage(),
					true);
			dataContainer.getStatusPanel().showLoadMessage(
					"Getting checkins from foursquare", false);
			fsSvc.getCheckinsFromFoursquare(result.getFoursquareId(),
					new FoursquareCheckinsCallback(fsSvc, dataContainer));
		}

		// if finished, show timed finished message
		else {
			dataContainer.getStatusPanel().showLoadMessage(result.getMessage(),
					true);
		}
	}
}
